import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  checkAllAction,
  delByIdAction,
  updateByIdAction,
} from '../store/action';

export default function Main() {
  // 原理：🔔useSelector在源码内部声明state，dispatch最终触发React的state变化，导致界面刷新
  const { list } = useSelector((state) => state);
  console.log('list -----> ', list);
  const isAll = list.length && list.every((item) => item.done);

  const dispatch = useDispatch();
  return (
    <section className="main">
      <input
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
        checked={isAll}
        onChange={(e) => dispatch(checkAllAction(e.target.checked))}
      />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {list.map((item) => {
          return (
            <li className={item.done ? 'completed' : ''} key={item.id}>
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={item.done}
                  onChange={() => dispatch(updateByIdAction(item.id))}
                />
                <label>{item.name}</label>
                <button
                  className="destroy"
                  onClick={() => dispatch(delByIdAction(item.id))}
                ></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
